package com.example.facecompare.user.userinfo.controller;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.facecompare.common.tool.result.Result;
import com.example.facecompare.common.wechat.WxConstant;
import com.example.facecompare.user.img.entity.UserImg;
import com.example.facecompare.user.userinfo.entity.AuditData;
import com.example.facecompare.user.userinfo.entity.User;
import com.example.facecompare.user.userinfo.entity.UserAndImg;
import com.example.facecompare.user.userinfo.mapper.UserMapper;
import com.example.facecompare.user.userinfo.service.IUserService;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import io.netty.handler.codec.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tbb
 * @since 2023-07-31
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IUserService iUserService;

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String appSecret;

    /**
     * 获取用户的唯一标识openid
     *
     * @param code 前端返回的有效码，用于获取openid的参数
     * @return 返回openid给前端
     * @throws IOException
     */
    @GetMapping("/get/openid")
    private Result getOpenid(@RequestParam("code") String code) throws IOException {
        //code
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
                + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";

        //客户端
        OkHttpClient client = new OkHttpClient();
        //用url发起请求
        Request request = new Request.Builder().url(url).build();
        //拿到响应
        Response response = client.newCall(request).execute();
        //如果响应成功，打印返回值
        if (response.isSuccessful()) {
            String body = response.body().string();
            JSONObject jsonObject = JSON.parseObject(body);
            return Result.success(jsonObject);
        }
        return Result.error();
    }

    /**
     * 获取所有用户信息
     *
     * @return 成功返回列表数组
     */
    @GetMapping("/get/all")
    private Result getAllUserInfo() {

        return Result.success(userMapper.selectList(null));
    }

    /**
     * 添加或者更新新用户（员工）
     *
     * @param user 用户信息
     * @return 插入成功则为1，否则0
     */
    @PostMapping("/insert/info")
    private Result insertInfo(@RequestBody User user) {
        User user1 = userMapper.selectById(user.getOpenid());
        int insert;

        if (user1 != null) {
            insert = userMapper.updateById(user);
        } else {
            insert = userMapper.insert(user);
        }
        if (insert > 0) {
            return Result.success(user);
        }
        return Result.error();
    }

    /**
     * 插入用户信息（弃用，用下面的方法）
     * @param userAndImg 包含用户信息和图片路径信息
     * @return 成功信息
     */
    @PostMapping("/transfer/insert")
    private Result transferInsert(@RequestBody UserAndImg userAndImg) {

        iUserService.transferUserImg(userAndImg);
        return Result.success();
    }

    /**
     * 插入用户信息并且获取底库信息
     * @param user 前端用户信息参数
     * @return 返回用户信息及底库信息
     */
    @PostMapping("/transfer/insert/get/img/path")
    private Result transferGetImgPath(@RequestBody User user) {
        UserImg userImg = iUserService.transferImgPath(user);
        UserAndImg userAndImg = new UserAndImg();
        userAndImg.setUser(user);
        userAndImg.setUserImg(userImg);
        return Result.success(userAndImg);
    }

    /**
     * 通过openid获取用户信息
     * @param openid 用户openid
     * @return 返回一个用户信息
     */
    @GetMapping("/openid/get/info")
    private Result getIdUser(@RequestParam("openid") String openid) {
//        userMapper.selectById(id);
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("openid",openid);
        return Result.success(userMapper.selectById(openid));
    }

    /**
     * 分页查询用户信息
     * @param index 从第几个开始查询
     * @param count 查询多少个
     * @return 查询对应数量的用户信息
     */
    @GetMapping("/get/limit")
    private Result getLimit(@RequestParam("index") Integer index, @RequestParam("count") Integer count) {

        return Result.success(userMapper.getLimitInfo(index,count));
    }

    /**
     * 获取用户表总数
     * @return 总数
     */
    @GetMapping("/get/count")
    private Result getCount(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        return Result.success(userMapper.selectCount(queryWrapper));
    }

    /**
     * 查询对应审核情况的用户信息（如已通过、未通过）
     * @param no 传0（未审核）,1（已通过）,2（未通过）
     * @param index 第几页
     * @param count 页数数量
     * @return
     */
    @GetMapping("/get/audit/data")
    private Result getAuditData(@RequestParam("no") Integer no,
                                @RequestParam("index") Integer index,
                                @RequestParam("count") Integer count){
        Page<User> userPage = new Page<>(index, count);
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("info_check",no);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//        添加过滤条件
        queryWrapper.eq(User::getInfoCheck,no);
//        添加排序条件
//        queryWrapper.orderByDesc(Employee::getUpdateTime);
//        执行查询

        Page<User> page = userMapper.selectPage(userPage, queryWrapper);
//        List<User> users = userMapper.selectList(queryWrapper);
//        Long aLong = userMapper.selectCount(queryWrapper);
//        AuditData auditData = new AuditData();
//        auditData.setUsers(userPage.getRecords());
//        auditData.setALong(userPage.getTotal());

        return Result.success(page);
    }
    /**
     * 通过名字模糊查询
     * @return 查询到的用户
     */
    @GetMapping("/get/like/name")
    private Result getLikeUser(@RequestParam("name") String name){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("uname",name);
        return Result.success(userMapper.selectList(queryWrapper));
    }

    /**
     * 获取access_token
     * @return 返回access_token
     */
//    @GetMapping("/get/access/token")
//    public Result getAccessToken() {
//        //获取访问用户身份的access_token
////        String access_token = AuthUtil.doGetJson(tokenUrl).get("access_token").toString();
//        String tokenUrl = String.format(WxConstant.WX_GET_TOKEN_URL, WxConstant.WX_APP_ID, WxConstant.WX_SECRENT);
//        log.info("access_token的url请求,access_token_url={}", tokenUrl);
//        RestTemplate restTemplate = new RestTemplate();
//        String response = restTemplate.getForObject(tokenUrl, String.class);
//        JSONObject jsonObject = JSONObject.parseObject(response);
//        String access_token = jsonObject.getString("access_token");
//        log.info("【访问用户身份access_token】,access_token={}", access_token);
//        return Result.success(access_token);
//    }

    /**
     * 获取userid唯一标识
     * @param code 由前端返回code
     * @return 返回userid
     */
    @GetMapping("/get/userid")
    public Result getCode(@RequestParam("code") String code) {
        log.info("code信息:{}",code);
        String tokenUrl = String.format(WxConstant.WX_GET_TOKEN_URL, WxConstant.WX_APP_ID, WxConstant.WX_SECRENT);
        log.info("access_token的url请求,access_token_url={}", tokenUrl);

        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(tokenUrl, String.class);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String access_token = jsonObject.getString("access_token");
        log.info("【访问用户身份access_token】,access_token={}", access_token);

        //获取userId
        RestTemplate restTemplate2 = new RestTemplate();
        String reqUrl2 = String.format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=%s&code=%s", access_token, code);
        String response2 = restTemplate2.getForObject(reqUrl2, String.class);

//        String result = HttpUtil.getResult("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE".replace("ACCESS_TOKEN", "").replace("CODE", code));
        JSONObject jsonObject2 = JSONObject.parseObject(response2);
        log.info("获取数据 {}",jsonObject2);
        String userId = jsonObject2.getString("UserId");
        if(!jsonObject2.containsKey("UserId")){
            userId = jsonObject2.getString("OpenId");
        }
        log.info(response2);
        return Result.success(userId);
    }

    //其他获取UserId的方法
    /**
     * 系统路径构建
     *
     * @return
     */
//    @GetMapping("/build/code")
//    public String buildCode() {
//        String buildUrl = "";
//        //回调地址
//        String url = "https%3A%2F%2Fauth.sjht.com%2Fuser%2Fget%2Fcode%2Fuserid";
//        return "redirect:" + "https://open.weixin.qq.com/connect/oauth2/authorize"
//                + "?appid=ww930d12930d5cc0d3"//企业id
//                + "&redirect_uri=https%3A%2F%2Fauth.sjht.com%2Fuser%2Fget%2Fcode%2Fuserid"//回调地址
//                + "&response_type=code"//固定填写
//                + "&scope=snsapi_base"//固定填写
//                + "&state=STATE"//自定义字段
//                + "#wechat_redirect";
//    }
//
//    //网页授权方式查看业务方法页面
//    @GetMapping("/get/auth")
//    public String auth() throws IOException {
//        log.info("进入到微信页面自定义方法地址...");
//        //拼接微信网页授权地址
//        String redirectURL = String.format(WxConstant.WX_CONNECT_OAUTH2_AUTHORIZE_URL, WxConstant.WX_APP_ID, WxConstant.REQUEST_URL,
//                WxConstant.WX_SNSAPI_BASE, StringUtils.trimToEmpty(WxConstant.WX_STATE),WxConstant.WX_AGENTID);
//        log.info("【微信网页授权】获取redirectURL,redirectURL={}", redirectURL);
////        response.sendRedirect(redirectURL);
//        return "redirect:" + redirectURL;
//    }
//
//    //回调地址调用
//    @RequestMapping("/get/userinfo")
//    public String userinfo(@RequestParam("code") String code) {
//        log.info("进入到回调地址...");
////        String code=req.getParameter("code");
//        log.info("【回调地址】获取的code值为{}", code);
//        try {
//            if (!"authdeny".equals(code)) {
//                //拼装获取access_token的url请求
//                String tokenUrl = String.format(WxConstant.WX_GET_TOKEN_URL, WxConstant.WX_APP_ID, WxConstant.WX_SECRENT);
//                log.info("access_token的url请求,access_token_url={}", tokenUrl);
//                //获取访问用户身份的access_token
////                String access_token =  AuthUtil.doGetJson(tokenUrl).get("access_token").toString();
//                RestTemplate restTemplate = new RestTemplate();
//                String response = restTemplate.getForObject(tokenUrl, String.class);
//                JSONObject jsonObject = JSONObject.parseObject(response);
//                String access_token = jsonObject.getString("access_token");
//                log.info("【访问用户身份access_token】,access_token={}", access_token);
//
//                //拼装获取访问用户身份的userid的url请求
//                String useridURL = WxConstant.WX_GET_USERID_URL.replace("ACCESS_TOKEN", access_token).replace("CODE", code);
//                //获取访问用户身份的基本信息（如userid）
////                JSONObject obj=AuthUtil.doGetJson(useridURL);
//                //获取userId
//                RestTemplate restTemplate2 = new RestTemplate();
//                String reqUrl2 = String.format(WxConstant.WX_GET_USERID_URL, access_token, code);
//                log.info("用户身份请求地址:{}",reqUrl2);
//                String response2 = restTemplate2.getForObject(reqUrl2, String.class);
//                JSONObject jsonObject2 = JSONObject.parseObject(response2);
//                String userId = jsonObject2.getString("UserId");
//
//                log.info("【访问用户身份基本信息】,obj={}", jsonObject2);
//                return userId;
//                //拼装获取访问用户身份详细信息的url请求
////                String userurl = WxConstant.WX_GET_USERINFO_URL.replace("ACCESS_TOKEN", access_token).replace("USERID", obj.getString("UserId"));
////                //获取访问用户身份的详细信息
////                JSONObject userInfo=AuthUtil.doGetJson(userurl);
////                log.info("【访问用户身份详细信息】,userInfo={}",userInfo);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "error";
//        }
//        return "未获取";
//    }
}

